﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Reflection;

namespace Grizzy_X
{
    public partial class MainForm : Form
    {
        public static Childform f1;
        public Childform f2;
        public TreeNode ParentNode;
        public TreeNode ParentBaseNode;
        public TreeNode ChildNode;
        public CMap map;
        public static MainForm pMainWin = null;
        public Cursor HandCursor;
        public Cursor ZoominCursor;
        public MainForm()
        {
            InitializeComponent();
            ParentNode = new TreeNode("地图名称");
            ParentNode.Name = "Layerlist"; ParentBaseNode = new TreeNode("底图列表");
            ParentBaseNode.Name = "Baselist";
            LayerTree.Nodes.Add(ParentNode);
            LayerTree.Nodes.Add(ParentBaseNode);
            ParentNode.Checked = true;
            ParentBaseNode.Checked = true;
            pMainWin = this;
            string curName = "Grizzy_X.Resources.十字叉.cur";
            System.IO.Stream stream = this.GetType().Assembly.GetManifestResourceStream(curName);
            HandCursor = new Cursor (stream);
            string zoomcur = "Grizzy_X.Resources.zoom.cur";
            stream = this.GetType().Assembly.GetManifestResourceStream(zoomcur);
            ZoominCursor = new Cursor(stream);
        }
        public Splash splash = new Splash();

        private void Form1_Load(object sender, EventArgs e)
        {
            /* System.Timers.Timer t = new System.Timers.Timer(4000);//实例化Timer类，设置间隔时间为10000毫秒； 
             t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到达时间的时候执行事件； 
             t.AutoReset = false;//设置是执行一次（false）还是一直执行(true)； 
             t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件
             this.Opacity = 0;
             splash.Show();*/

            StartForm startform = new StartForm();
            startform.ShowDialog();
            if (Controller.StartOperation == "Open")
                OpenMap.PerformClick();
            if (Controller.StartOperation == "New")
                NewMap.PerformClick();
            LineRst.SelectedIndex = 0;
            GraphRst.SelectedIndex = 0;


            // Control.CheckForIllegalCrossThreadCalls = false;//设置属性可以跨线程访问
        }

        /* public void theout(object source, System.Timers.ElapsedEventArgs e)
         {
             this.Opacity = 1;
             splash.Close();
             StartForm startform = new StartForm();
             ThreadSafeWay(null, startform);
             /*if (Controller.check)
             {
                 Controller.check = false;
                 this.NewMap.PerformClick();
             }
             Control.CheckForIllegalCrossThreadCalls = true;  //将此属性修改回来
         }

         //保证线程安全
         private delegate DialogResult FormDelegate(object msg, object form);
         public DialogResult ThreadSafeWay(object msg, object form)
         {
             FormDelegate controlDelegate = new FormDelegate(ThreadSafeWay);
             if ((this as Form).InvokeRequired)
             {
                 return (DialogResult)(this as Form).Invoke(controlDelegate, new object[] { msg, form });
             }
             else
             {
                 return (form as Form).ShowDialog(this);
             }
         }*/


        private void Save_Click(object sender, EventArgs e)
        {
            Persistance.SaveMap();
        }

        private void Layer_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //LayerTree.ContextMenuStrip = null;
        }

        public void Newmap_Click(object sender, EventArgs e)
        {
            NewMapForm newmapform = new NewMapForm();
            newmapform.ShowDialog();
            if (Controller.check == true)
            {
                panelmdi.Visible = true;

                if (Controller.CountForm == 0)
                {
                    //实例化的位置？？？？
                    //map = new CMap();
                    // map.New(Controller.mapname, newmapform.Height, newmapform.Width, newmapform.MapPath,newmapform.MapDes);
                    f1 = new Childform();
                    Controller.CountForm++;
                    f1.FormBorderStyle = FormBorderStyle.None;
                    f1.Height = 464;
                    f1.Width = 758;
                    f1.MdiParent = this;
                    f1.Parent = this.panelmdi;
                    f1.Text = "子窗体" + Controller.CountForm;
                    if (this.WindowState == FormWindowState.Maximized)
                    {
                        f1.Width = 1080;
                        f1.Height = 701;
                    }
                    f1.Show();
                    MapButton();
                    ParentNode.Text = Controller.mapname;
                }
                Controller.check = false;
                toolStripStatusUnit.Text += Controller.MyMap.Unit;
                toolStripStatusLabelScale.Text+= "1:1";
            }
        }
        private void NewLayer_Click(object sender, EventArgs e)
        {
            NewLayerForm newlayerform = new NewLayerForm();
            newlayerform.ShowDialog();
            if (Controller.check)
            {
                f1.AddLayer();
                
                Controller.check = false;
                LayerButton();
                ChildNode = new TreeNode(newlayerform.layername);
                CurrentLayerCombo.DataSource = null;
                CurrentLayerCombo.DataSource = Controller.MyMap.Layer_List;
                CurrentLayerCombo.DisplayMember = "GetName";
                CurrentLayerCombo.SelectedIndex = Controller.CountLayer - 1;
                ChildNode.Name = "childnode" + Controller.CountLayer;
                ChildNode.ImageIndex = 1;
                ChildNode.SelectedImageIndex = 1;
                ParentNode.Nodes.Insert(0, ChildNode);
                ChildNode.Checked = true;
                LayerTree.ExpandAll();
                Controller.current_Operation = Controller.OperationStyles.None;
            }
        }
        private void Colorize_Click(object sender, EventArgs e)
        {
            colorDialog1.ShowDialog();
        }

        private void Font_Click(object sender, EventArgs e)
        {
            fontDialog1.ShowDialog();
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                logo.Visible = true;
            }
            if (Controller.CountForm != 0)
            {
                if (this.WindowState == FormWindowState.Maximized)
                {
                    f1.Width = 1080;
                    f1.Height = 701;
                }
                if (this.WindowState == FormWindowState.Normal)
                {
                    f1.Width = 758;
                    f1.Height = 464;
                }
            }
            else
            {//Save
            }
        }

        private void ShowMDI_Click(object sender, EventArgs e)
        {
            if (Controller.CountForm != 0)
            {

                Layer_View Lview = new Layer_View();
                if (Lview.ShowDialog() == DialogResult.OK)
                {
                    ChildView newCView = new ChildView(Lview.Display);
                    newCView.MdiParent = this;
                    newCView.Parent = this.panelmdi;
                    newCView.Text = "视图" + Controller.CountForm;
                    newCView.BringToFront();
                    newCView.Show();
                    Controller.CountForm++;
                }
            }
        }
        private TreeNode selectNode=new TreeNode ();
        private void Layer_MouseClick(object sender, MouseEventArgs e)
        {
            LayerTree.ContextMenuStrip = null;
            if (e.Button == MouseButtons.Right)
            {
                selectNode = LayerTree.GetNodeAt(e.X, e.Y);
                if (selectNode.Level == 1)
                {
                    LayerTree.ContextMenuStrip = LayerMenu;
                    LayerTree.SelectedNode = selectNode;
                }
                if (selectNode.Level == 0)
                {
                    LayerTree.ContextMenuStrip = MapMenu;
                    LayerTree.SelectedNode = selectNode;
                }
            }
        }
        private void Remove_Click(object sender, EventArgs e)
        {
            if (selectNode.Parent.Name == "Layerlist")
            {
                int RemoveID = Convert.ToInt16(selectNode.Name.Replace("childnode", ""));
                Controller.FindLayer(Controller.CurrentID).Dispose(); 
                //Controller.MyMap.Layer_List.RemoveAt(RemoveID-1);
                ParentNode.Nodes.Remove(selectNode);
                LayerTree.Refresh();
                Controller.CountLayer--;
                Controller.MyMap.ModifyLayerOrder();
                Controller.MyMap.RefreshLayerOrder(f1);
                if (RemoveID == Controller.CurrentID)
                {
                    try
                    {
                        Controller.CurrentID = Controller.MyMap.Layer_Order[0];
                    }
                    catch
                    {
                        Controller.CurrentID = 0;
                        return;
                    }
                }

                f1.Temp = Controller.FindLayer(Controller.CurrentID);
            }
        }

        private void Import_Click(object sender, EventArgs e)
        {
            ImportForm importform = new ImportForm();
            importform.ShowDialog();
            if (Controller.check)
            {
                f1.AddBase();
                ChildNode = new TreeNode(Controller.MyMap.BaseMap_List[Controller.CountBase - 1].Name);
                ChildNode.Name = "childnode" + Controller.CountBase;
                ChildNode.ImageIndex = 2;
                ChildNode.SelectedImageIndex = 2;
                ParentBaseNode.Nodes.Insert(0, ChildNode);
                ChildNode.Checked = true;
                LayerTree.ExpandAll();
                f1.TempBase.Image = Controller.MyMap.BaseMap_List[Controller.CountBase - 1].DrawBase();
                Controller.check = false;
            }
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void VisitWeb_Click(object sender, EventArgs e)
        {
            Process.Start("http://code.google.com/p/grizzy-x-betaversion/");

        }



        private void LayerMenu_Closed(object sender, ToolStripDropDownClosedEventArgs e)
        {
            LayerTree.ContextMenuStrip = null;
        }

        private void MapMenu_Closed(object sender, ToolStripDropDownClosedEventArgs e)
        {
            LayerTree.ContextMenuStrip = null;
        }

        private void ChangeLegend_Click(object sender, EventArgs e)
        {
            LegendForm legendform = new LegendForm();
            legendform.ShowDialog();
        }

        private bool ptLayerFirstLegend = true;
        private bool lnLayerFirstLegend = true;
        private bool plgLayerFirstLegend = true;
        private bool txLayerFirstLegend = true;
        //用户点击“编辑”按钮，开始矢量化画图
        private void Edit_Click(object sender, EventArgs e)
        {
            Controller.current_Operation = Controller.OperationStyles.Editing;
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPointLayer)
            {
                if (ptLayerFirstLegend == true)
                {
                    LegendForm legendform = new LegendForm();
                    legendform.firstRefresh();
                    legendform.ShowDialog();
                    ptLayerFirstLegend = false;
                }
                else
                {
                    EditLegendForm editLegendForm = new EditLegendForm();
                    editLegendForm.RefreshData();
                    editLegendForm.ShowDialog();
                }
            }
            else if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CLineLayer)
            {
                if (lnLayerFirstLegend == true)
                {
                    LegendForm legendform = new LegendForm();
                    legendform.firstRefresh();
                    legendform.ShowDialog();
                    lnLayerFirstLegend = false;
                }
                else
                {
                    EditLegendForm editLegendForm = new EditLegendForm();
                    editLegendForm.RefreshData();
                    editLegendForm.ShowDialog();
                }
            }
            else if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPolygonLayer)
            {
                if (plgLayerFirstLegend == true)
                {
                    LegendForm legendform = new LegendForm();
                    legendform.firstRefresh();
                    legendform.ShowDialog();
                    plgLayerFirstLegend = false;
                }
                else
                {
                    EditLegendForm editLegendForm = new EditLegendForm();
                    editLegendForm.RefreshData();
                    editLegendForm.ShowDialog();
                }
            }
            else
            {
                if (txLayerFirstLegend == true)
                {
                        LegendForm legendform = new LegendForm();
                        legendform.firstRefresh();
                        legendform.ShowDialog();
                        txLayerFirstLegend = false;
                    }
                    else
                    {
                        EditLegendForm editLegendForm = new EditLegendForm();
                        editLegendForm.RefreshData();
                        editLegendForm.ShowDialog();
                    }
                
            }
            //f1.Cursor = HandCursor;
            EditButton();
            //f1.current_objectnum++;
            RefreshComboOrder();
            Controller.MyMap.RefreshLayerOrder(f1); 
            TextEdit.Enabled = true;//wx 
        }

        private void MapButton()
        {
            if (Controller.DBExists == false)     //未建数据库时，数据库是可用的
            {
                NewDB.Enabled = true;
            }
            NewLayer.Enabled = true;
            Save.Enabled = true;
            AddLayer.Enabled = true;
            Import.Enabled = true;
            Export.Enabled = true;
        }
        private void LayerButton()
        {
            if (Controller.DBExists == false)     //未建数据库时，数据库是可用的
            {
                NewDB.Enabled = true;
            } 
            toolStriptool.Enabled = true;
            toolStriptool.Enabled = true;
            toolStripedit.Enabled = true;

            Zoomin.Enabled = true;
            Zoomout.Enabled = true;
            Position.Enabled = true;
            ShowMDI.Enabled = true;
            Properties.Enabled = true;
            Pan.Enabled = true;
            //Drag.Enabled = true;
            Select.Enabled = true;
            Edit.Enabled = true;
            Write.Enabled = true;
            Legend.Enabled = true;
            Colorize.Enabled = true;
            Font.Enabled = true;
            CurrentLayerCombo.Enabled = true;
        }
        public void EditButton()//wx 有所改动
        {
            Finish.Enabled = true;
            Edit.Enabled = false;
            Undo.Enabled = true;
            Select.Enabled = false;

            CurrentLayerCombo.Enabled = false;
            //f1.current_objectnum++;
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CTextLayer)
                TextEdit.Enabled = true;
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPointLayer)
            {
                f1.Temp.ContextMenuStrip = f1.cmMenu1;
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CLineLayer)
            {
                f1.Temp.ContextMenuStrip = f1.cmMenu2;
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPolygonLayer)
            {
                f1.Temp.ContextMenuStrip = f1.cmMenu3;
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CTextLayer)
            {
                f1.Temp.ContextMenuStrip = f1.cmMenu4;
            }
            f1.Cursor = HandCursor;
        }
        public void FinishButton()
        {
            Select.Enabled = true;
            Edit.Enabled = true;
            Copy.Enabled = false;
            Paste.Enabled = false;
            Island.Enabled = false;
            Delete.Enabled = false;
            Split.Enabled = false;
            Union.Enabled = false;
            f1.Cursor = Cursors.Arrow;
            Finish.Enabled = false;
            Drag.Enabled = true;
            TextEdit.Enabled = false;
        }
        public void SelectButton()
        {
            //select.Enabled = false;
            Copy.Enabled = true;
            Paste.Enabled = true;
            //Cut.Enabled = true;
            Delete.Enabled = true;
            //Union.Enabled = true;
            //wx的改动
            Edit.Enabled = false;
            Finish.Enabled = true;
            if (Controller.CurrentLayer.Layer_Type ==CLayer.LayerType.CLineLayer || Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPolygonLayer)
            {
                SnapEdge.Enabled = true;
                SnapPoint.Enabled = true;
            }
            CurrentLayerCombo.Enabled = false;
            //Drag.Enabled = true;
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPointLayer)
            {
               // f1.pt_增加点xyToolStripMenuItem.Enabled = true;
                f1.pt_复制ToolStripMenuItem.Enabled = true;
                f1.pt_继续画ToolStripMenuItem.Enabled = true;
               // f1.pt_剪切ToolStripMenuItem.Enabled = true;
                f1.pt_结束编辑ToolStripMenuItem.Enabled = true;
                f1.pt_删除ToolStripMenuItem.Enabled = true;
               // f1.pt_修改属性ToolStripMenuItem.Enabled = true;
                f1.pt_选择简单点ToolStripMenuItem.Enabled = true;
               // f1.pt_移动到ToolStripMenuItem.Enabled = true;
                f1.Temp.ContextMenuStrip = f1.cmMenu1;
                //f1.Temp.Image = ((CPointLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawpoint();
                //f1.pt_增加点xyToolStripMenuItem.Enabled = true;
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CLineLayer)
            {
                f1.Temp.ContextMenuStrip = f1.cmMenu2;
                f1.ln_编辑节点ToolStripMenuItem.Enabled = true;
                f1.ln_复制ToolStripMenuItem.Enabled = true;
                f1.ln_继续画ToolStripMenuItem1.Enabled = true;
                //f1.ln_剪切ToolStripMenuItem1.Enabled = true;
                f1.ln_结束编辑ToolStripMenuItem1.Enabled = true;
                f1.ln_删除ToolStripMenuItem1.Enabled = true;
                //f1.ln_修改属性ToolStripMenuItem1.Enabled = true;
                f1.ln_选择简单线ToolStripMenuItem.Enabled = true;
                //f1.ln_移动偏移量ToolStripMenuItem.Enabled = true;
                //f1.ln_增加节点到xyToolStripMenuItem.Enabled = true;
                //f1.Temp.Image = ((CLineLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawlinelayer();
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPolygonLayer)
            {
                f1.Temp.ContextMenuStrip = f1.cmMenu3;
                f1.plgn_编辑节点ToolStripMenuItem1.Enabled = true;
                f1.plgn_复制ToolStripMenuItem1.Enabled = true;
                f1.plgn_继续画ToolStripMenuItem2.Enabled = true;
                //f1.plgn_剪切ToolStripMenuItem2.Enabled = true;
                f1.plgn_结束编辑ToolStripMenuItem3.Enabled = true;
                f1.plgn_删除ToolStripMenuItem4.Enabled = true;
                //f1.plgn_修改属性ToolStripMenuItem2.Enabled = true;
                f1.plgn_选择简单多边形ToolStripMenuItem.Enabled = true;
               // f1.plgn_移动偏移量ToolStripMenuItem1.Enabled = true;
                //f1.plgn_增加节点到xyToolStripMenuItem1.Enabled = true;
                //f1.Temp.Image = ((CPolygonLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawpolygon();
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CTextLayer)
            {
                 f1.Temp.ContextMenuStrip = f1.cmMenu4;
                f1.tx_复制ToolStripMenuItem2.Enabled = true;
                f1.tx_继续编辑ToolStripMenuItem.Enabled = true;
                //f1.tx_剪切ToolStripMenuItem3.Enabled = true;
                f1.tx_结束编辑ToolStripMenuItem2.Enabled = true;
                f1.tx_删除ToolStripMenuItem3.Enabled = true;
                //f1.tx_修改属性ToolStripMenuItem3.Enabled = true;
                f1.tx_选择简单文本ToolStripMenuItem.Enabled = true;
                //f1.tx_移动textToolStripMenuItem2.Enabled = true;
                //f1.tx_增加文本到xyToolStripMenuItem.Enabled = true;
                //f1.Temp.Image = ((CTextLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawtext();
            }
            CurrentLayerCombo.Enabled = true;
        }
        private void ChildForm_Move(object sender, EventArgs e)
        {
            if (f2.Location.Y < 0)
                f2.Location = new Point(f2.Location.X, 0);
        }

        private void Donate_Click(object sender, EventArgs e)
        {
            Process.Start("http://code.google.com/p/grizzy-x-betaversion/wiki/DonateUs");
        }

        private void ClearSelected()
        {
            if(Controller.selectsimple!=null)
                    Controller.selectsimple.Clear();
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPointLayer)
            {
                f1.Cpointlist = new List<CPoint>();
                f1.pt_复制ToolStripMenuItem.Enabled = false;
                f1.pt_继续画ToolStripMenuItem.Enabled = false;
                f1.pt_结束编辑ToolStripMenuItem.Enabled = false;
                f1.pt_删除ToolStripMenuItem.Enabled = false;
                f1.pt_选择简单点ToolStripMenuItem.Enabled = false;
                f1.pt_粘贴ToolStripMenuItem.Enabled = false;
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CLineLayer)
            {
                f1.Clinelist = new List<CLine>();
                       f1.Temp.ContextMenuStrip = f1.cmMenu2;
                f1.ln_编辑节点ToolStripMenuItem.Enabled = false;
                f1.ln_复制ToolStripMenuItem.Enabled = false;
                f1.ln_继续画ToolStripMenuItem1.Enabled = false;
                f1.ln_结束编辑ToolStripMenuItem1.Enabled = false;
                f1.ln_删除ToolStripMenuItem1.Enabled = false;
                f1.ln_增加节点到xyToolStripMenuItem.Enabled = false;
                f1.ln_选择简单线ToolStripMenuItem.Enabled = false;
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPolygonLayer)
            {
                f1.Cpolygonlist = new List<CPolygon>();
                    f1.Temp.ContextMenuStrip = f1.cmMenu3;
                f1.plgn_编辑节点ToolStripMenuItem1.Enabled =false;
                f1.plgn_复制ToolStripMenuItem1.Enabled = false;
                f1.plgn_继续画ToolStripMenuItem2.Enabled = false;
                f1.plgn_结束编辑ToolStripMenuItem3.Enabled = false;
                f1.plgn_删除ToolStripMenuItem4.Enabled = false;
                f1.plgn_增加节点到xyToolStripMenuItem1.Enabled = false;
                f1.plgn_选择简单多边形ToolStripMenuItem.Enabled =false;
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CTextLayer)
            {
                f1.Ctextlist = new List<CText>();
               f1.Temp.ContextMenuStrip = f1.cmMenu4;
                f1.tx_复制ToolStripMenuItem2.Enabled = false;
                f1.tx_继续编辑ToolStripMenuItem.Enabled = false;
                f1.tx_结束编辑ToolStripMenuItem2.Enabled = false;
                f1.tx_删除ToolStripMenuItem3.Enabled = false ;
                f1.tx_选择简单文本ToolStripMenuItem.Enabled = false;
            }
                Controller.selectlineindex = new Point(-1, -1);
                Controller.selectnodeindex = new Point(-1,-1);
                f1.draggingnode = false;
                f1.draggingc = false;
                f1.draggingsimple = false;
                f1.selectsimple = false;
                f1.drawisland = false;
                f1.continuedraw = false;
                f1.addislandpolygon = false;
                Controller.current_Operation =Controller.OperationStyles.Selecting;
            if (Controller.Selected.Count!=0)
            {
                Controller.Selected.Clear();  
                if (Controller.SelectedObjectType == "Point")
                {
                    f1.Temp.Image = ((CPointLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawpoint();
                }
                if (Controller.SelectedObjectType == "Line")
                {
                    f1.Temp.Image = ((CLineLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawlinelayer();
                }
                if (Controller.SelectedObjectType == "Polygon")
                {
                    f1.Temp.Image = ((CPolygonLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawpolygon();
                }
                if (Controller.SelectedObjectType == "Text")
                {
                    f1.Temp.Image = ((CTextLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawtext();
                }
                Controller.SelectedObjectType = "None";
            }
        }

        private void Finish_Click(object sender, EventArgs e)
        {
            if (Controller.current_Operation == Controller.OperationStyles.Selecting||Controller.current_Operation==Controller.OperationStyles.Editnode)
                ClearSelected();
            CurrentLayerCombo.Enabled = true;
            Controller.current_Operation = Controller.OperationStyles.None;
            //Send the current layer back to original place
            if (Orderindex != -1)
            {
                int index = Controller.MyMap.Layer_Order[0];
                Controller.MyMap.Layer_Order.RemoveAt(0);
                Controller.MyMap.Layer_Order.Insert(Orderindex, index);
                Controller.MyMap.RefreshLayerOrder(f1);
                Orderindex = -1;
            }
            FinishButton();
        }


        //新建数据库
        private void NewDB_Click(object sender, EventArgs e)
        {
            if (Persistance.mdbPath == null)
            {
                Persistance.mdbPath = Controller.MapPath;

            }
            else
            {
                MessageBox.Show("警告：数据库已经存在,无法创建！");
            }
        }

        private void Zoomin_Click(object sender, EventArgs e)
        {
            Controller.current_Operation = Controller.OperationStyles.Zoomin;
            //f1.Temp.Cursor = ZoominCursor;
            f1.Cursor = ZoominCursor;
        }



        //用户点击“图例”按钮，开始对已有图例进行编辑
        private void Legend_Click(object sender, EventArgs e)
        {
            EditLegendForm editLegendForm = new EditLegendForm();
            editLegendForm.RefreshData();
            editLegendForm.ShowDialog();
        }


        private void Zoomout_Click(object sender, EventArgs e)
        {
            Controller.current_Operation = Controller.OperationStyles.Zoomout;
            f1.Cursor = ZoominCursor;
        }


        //实现ZoomToLayer功能
        private void Position_Click(object sender, EventArgs e)
        {
            Controller.current_Operation = Controller.OperationStyles.Zoomtolayer;
            f1.curViewer.ZoomToLayer();
            toolStripStatusLabelScale.Text = "显示比例：1:" +f1.curViewer.GetScale().ToString();
            Controller.Draw_Layer();
            f1.Cursor = Cursors.Arrow;
        }

        private void LayerTree_AfterCheck(object sender, TreeViewEventArgs e)
        {
            PictureBox TempV = new PictureBox();
            if (e.Node.Name != "Layerlist" && e.Node.Name != "Baselist" && e.Node.Parent.Name == "Layerlist")
            {
                int SelectID = Convert.ToInt16(e.Node.Name.Replace("childnode", ""));
                //wx修改
                if (e.Node.Checked && e.Node.Parent.Checked)
                    Controller.MyMap.Layer_List[SelectID - 1].bVisible = true;
                else
                    Controller.MyMap.Layer_List[SelectID - 1].bVisible = false;
                if (Controller.MyMap.Layer_List[SelectID - 1].Layer_Type == CLayer.LayerType.CPointLayer)
                {
                    if (((CPointLayer)Controller.MyMap.Layer_List[SelectID - 1]).ptlayer != null)
                    {
                        TempV = Controller.FindLayer(SelectID);
                        if (TempV == null)
                            return;
                        if (e.Node.Checked && e.Node.Parent.Checked)
                            TempV.Image = ((CPointLayer)Controller.MyMap.Layer_List[SelectID - 1]).ptlayer;
                        else
                            TempV.Image = Controller.Blank;
                    }
                }
                else if (Controller.MyMap.Layer_List[SelectID - 1].Layer_Type == CLayer.LayerType.CLineLayer)
                {
                    if (((CLineLayer)Controller.MyMap.Layer_List[SelectID - 1]).lnlayer != null)
                    {
                        TempV = Controller.FindLayer(SelectID);
                        if (TempV == null)
                            return;
                        if (e.Node.Checked && e.Node.Parent.Checked)
                            TempV.Image = ((CLineLayer)Controller.MyMap.Layer_List[SelectID - 1]).lnlayer;
                        else
                            TempV.Image = Controller.Blank;
                    }
                }
                else if (Controller.MyMap.Layer_List[SelectID - 1].Layer_Type == CLayer.LayerType.CPolygonLayer)
                {
                    if (((CPolygonLayer)Controller.MyMap.Layer_List[SelectID - 1]).pnlayer != null)
                    {
                        TempV = Controller.FindLayer(SelectID);
                        if (TempV == null)
                            return;
                        if (e.Node.Checked && e.Node.Parent.Checked)
                            TempV.Image = ((CPolygonLayer)Controller.MyMap.Layer_List[SelectID - 1]).pnlayer;
                        else
                            TempV.Image = Controller.Blank;
                    }
                }
                else if (Controller.MyMap.Layer_List[SelectID - 1].Layer_Type == CLayer.LayerType.CTextLayer)
                {
                    if (((CTextLayer)Controller.MyMap.Layer_List[SelectID - 1]).txlayer != null)
                    {
                        TempV = Controller.FindLayer(SelectID);
                        if (TempV == null)
                            return;
                        if (e.Node.Checked && e.Node.Parent.Checked)
                            TempV.Image = ((CTextLayer)Controller.MyMap.Layer_List[SelectID - 1]).txlayer;
                        else
                            TempV.Image = Controller.Blank;
                    }
                }
            }
            if (e.Node.Name != "Layerlist" && e.Node.Name != "Baselist" && e.Node.Parent.Name == "Baselist")
            {
                int SelectID = Convert.ToInt16(e.Node.Name.Replace("childnode", ""));
                if (Controller.MyMap.BaseMap_List[SelectID - 1].basebmp != null)
                {
                    TempV = Controller.FindBase(SelectID);
                    if (TempV == null)
                        return;
                    if (e.Node.Checked && e.Node.Parent.Checked)
                    {
                        TempV.Image = Controller.MyMap.BaseMap_List[SelectID - 1].basebmp;
                        Controller.MyMap.BaseMap_List[SelectID - 1].Visible = true;
                    }
                    else
                    {
                        TempV.Image = Controller.Blank;
                        Controller.MyMap.BaseMap_List[SelectID - 1].Visible = false;
                    }
                }
            }
            if (e.Node.Name == "Layerlist")
            {
                for (int i = 0; i < Controller.CountLayer; i++)
                {
                    TempV = Controller.FindLayer(i + 1);
                    if (e.Node.Checked)
                    {
                        Controller.MyMap.Layer_List[i].bVisible = true;
                        if (Controller.MyMap.Layer_List[i].Layer_Type == CLayer.LayerType.CPointLayer)
                            TempV.Image = ((CPointLayer)Controller.MyMap.Layer_List[i]).ptlayer;
                        if (Controller.MyMap.Layer_List[i].Layer_Type == CLayer.LayerType.CLineLayer)
                            TempV.Image = ((CLineLayer)Controller.MyMap.Layer_List[i]).lnlayer;
                        if (Controller.MyMap.Layer_List[i].Layer_Type == CLayer.LayerType.CPolygonLayer)
                            TempV.Image = ((CPolygonLayer)Controller.MyMap.Layer_List[i]).pnlayer;
                        if (Controller.MyMap.Layer_List[i].Layer_Type == CLayer.LayerType.CTextLayer)
                            TempV.Image = ((CTextLayer)Controller.MyMap.Layer_List[i]).txlayer;
                    }
                    if (!e.Node.Checked)
                    {
                        TempV.Image = Controller.Blank;
                        Controller.MyMap.Layer_List[i].bVisible = false;
                    }
                }
            }
            if (e.Node.Name == "Baselist")
            {
                for (int i = 0; i < Controller.CountBase; i++)
                {
                    TempV = Controller.FindBase(i + 1);
                    if (e.Node.Checked)
                    {
                        Controller.MyMap.BaseMap_List[i].Visible = true;
                        TempV.Image = Controller.MyMap.BaseMap_List[i].basebmp;
                    }
                    if (!e.Node.Checked)
                    {
                        Controller.MyMap.BaseMap_List[i].Visible = false;
                        TempV.Image = Controller.Blank;
                    }
                }
            }
        }

        int Orderindex = -1;
        private void RefreshComboOrder()
        {
            if (Orderindex != -1)
            {
                int index = Controller.MyMap.Layer_Order[0];
                Controller.MyMap.Layer_Order.RemoveAt(0);
                Controller.MyMap.Layer_Order.Insert(Orderindex, index);
            }
            Orderindex = Controller.MyMap.Layer_Order.IndexOf(CurrentLayerCombo.SelectedIndex + 1);
            Controller.MyMap.Layer_Order.Remove(CurrentLayerCombo.SelectedIndex + 1);
            Controller.MyMap.Layer_Order.Insert(0, CurrentLayerCombo.SelectedIndex + 1);
        }

        private void Select_Click(object sender, EventArgs e)
        {
            ClearSelected();
            SelectButton();
            RefreshComboOrder();
            Controller.MyMap.RefreshLayerOrder(f1);
            Controller.current_Operation = Controller.OperationStyles.Selecting;
        }

        private void Drag_Click(object sender, EventArgs e)
        {
            //Hand.Enabled = false;
            //Select.Enabled = true;
            f1.Cursor = Cursors.Hand;
            Edit.Enabled = false;
            if (Controller.Selected.Count() == 0)
                Controller.current_Operation = Controller.OperationStyles.Panning;
            if (Controller.selectsimple == null && Controller.selectnodeindex.X == -1)
            {
                f1.draggingc = true;
                f1.draggingsimple = false;
                f1.draggingnode = false;
            }
            if (Controller.selectsimple != null)
            {
                if (Controller.selectnodeindex.X == -1 && Controller.selectsimple.Count == 0)
                {
                    f1.draggingc = true;
                    f1.draggingsimple = false;
                    f1.draggingnode = false;
                }
                else if (Controller.selectsimple.Count() > 0 && Controller.selectnodeindex.X == -1)
                {
                    f1.draggingc = false;
                    f1.draggingsimple = true;
                    f1.draggingnode = false;
                }
            }
            if (Controller.selectnodeindex.X != -1)
            {
                f1.draggingc = false;
                f1.draggingsimple = false;
                f1.draggingnode = true;
                int i = 0;
            }
        }

        private void Export_Click(object sender, EventArgs e)
        {
            Persistance.ExportMap();
        }

        //打开当前图层的属性表
        private void Properties_Click(object sender, EventArgs e)
        {
            attri_Table attriTable = new attri_Table();
            attriTable.ShowDialog();
        }
        public TreeNode SelectedNode;
        private void LayerTree_ItemDrag(object sender, ItemDragEventArgs e)
        {
            SelectedNode = (TreeNode)e.Item;
            if (SelectedNode.Name != "Baselist" && SelectedNode.Name != "Layerlist")
            {
                DoDragDrop(e.Item, DragDropEffects.Move);
            }
        }
        private void LayerTree_DragOver(object sender, DragEventArgs e)
        {
            if ((SelectedNode.Parent.Name == "Baselist") || (SelectedNode.Parent.Name == "Layerlist" && Controller.current_Operation != Controller.OperationStyles.Editing
                && Controller.current_Operation != Controller.OperationStyles.Selecting && Controller.current_Operation != Controller.OperationStyles.Dragging))
            {
                SelectedNode.ForeColor = Color.DarkGray;
                Point pt;
                pt = ((TreeView)(sender)).PointToClient(new Point(e.X, e.Y));
                TreeNode Objdata = this.LayerTree.GetNodeAt(pt);
                if (SelectedNode == Objdata)
                    return;
                if (Objdata != null)
                {
                    if (Objdata.Name == SelectedNode.Parent.Name)
                    {
                        e.Effect = DragDropEffects.Move;
                        SelectedNode.Parent.Nodes.Remove(SelectedNode);
                        Objdata.Nodes.Insert(0, SelectedNode);
                        return;
                    }
                    if (Objdata.Parent.Name == SelectedNode.Parent.Name)
                    {
                        e.Effect = DragDropEffects.Move;
                        SelectedNode.Parent.Nodes.Remove(SelectedNode);
                        Objdata.Parent.Nodes.Insert(Objdata.Index + 1, SelectedNode);
                    }
                    else
                    {
                        e.Effect = DragDropEffects.None;
                        SelectedNode.ForeColor = Color.Black;
                    }
                }
            }
            else
                e.Effect = DragDropEffects.None;
        }
        private void LayerTree_DragDrop(object sender, DragEventArgs e)
        {
            SelectedNode.ForeColor = Color.Black;
            if (SelectedNode.Parent.Name == "Layerlist")
            {
                Controller.MyMap.ModifyLayerOrder();
                Controller.MyMap.RefreshLayerOrder(f1);
            }
            if (SelectedNode.Parent.Name == "Baselist")
            {
                Controller.MyMap.ModifyBaseOrder();
                Controller.MyMap.RefreshBaseOrder(f1);
            }
        }
        private void LayerTree_DragLeave(object sender, EventArgs e)
        {
            SelectedNode.ForeColor = Color.Black;
        }


        private void Pan_Click(object sender, EventArgs e)
        {
            f1.Cursor = Cursors.NoMove2D;
            Controller.current_Operation = Controller.OperationStyles.Panning;
        }

        private void Split_Click(object sender, EventArgs e)
        {
            Split.Enabled = false;
            f1.Cursor = HandCursor;
            if(Controller.SelectedObjectType=="Line")
                Controller.current_Operation = Controller.OperationStyles.SplitLine;
            if (Controller.SelectedObjectType == "Polygon")
            {
                Controller.current_Operation = Controller.OperationStyles.SplitPolygon;
                f1.Temp.ContextMenuStrip = null;
            }
        }

        public bool textchanged = false;
        private void TextEdit_TextChanged(object sender, EventArgs e)
        {
            if (Controller.Selected != null)
            {
                if (Controller.Selected.Count() == 1)
                {
                    if (((CTextLayer)Controller.MyMap.Layer_List[Controller.CountLayer - 1]).Text_Set[Controller.Selected[0]].points.Count() == 1)
                        textchanged = true;
                }
            }
            if (Controller.selectsimple != null)
            {
                if (Controller.selectsimple.Count() == 1)
                {
                    textchanged = true;
                }
            }
        }

        private void CurrentLayerCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (CurrentLayerCombo.SelectedIndex != -1)
            {
                Controller.CurrentLayer = Controller.MyMap.Layer_List[CurrentLayerCombo.SelectedIndex];
                Controller.CurrentID = CurrentLayerCombo.SelectedIndex + 1;
                f1.Cpointlist = new List<CPoint>();
                f1.Clinelist = new List<CLine>();
                f1.Cpolygonlist = new List<CPolygon>();
                f1.Ctextlist = new List<CText>();
                f1.current_objectnum = 0;
                f1.dclick = true;
                f1.click = false;
            }
        }

        private void Union_Click(object sender, EventArgs e)
        {
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPointLayer)
            {
                ((CPointLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).Union();
                f1.Temp.Image = ((CPointLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawpoint();
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CLineLayer)
            {
                ((CLineLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).Union();
                f1.Temp.Image = ((CLineLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawlinelayer();
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPolygonLayer)
            {
                ((CPolygonLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).Union();
                f1.Temp.Image = ((CPolygonLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawpolygon();
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CTextLayer)
            {
                ((CTextLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).Union();
                f1.Temp.Image = ((CTextLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawtext();
            }
            MainForm.pMainWin.Ununion.Enabled = true;
        }

        private void Ununion_Click(object sender, EventArgs e)
        {
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPointLayer)
            {
                ((CPointLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).unUnion();
                f1.Temp.Image = ((CPointLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawpoint();
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CLineLayer)
            {
                ((CLineLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).unUnion();
                f1.Temp.Image = ((CLineLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawlinelayer();
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPolygonLayer)
            {
                ((CPolygonLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).unUnion();
                f1.Temp.Image = ((CPolygonLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawpolygon();
            }
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CTextLayer)
            {
                ((CTextLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).unUnion();
                f1.Temp.Image = ((CTextLayer)Controller.MyMap.Layer_List[Controller.CurrentID - 1]).drawtext();
            }
        }

        private void AddLayer_Click(object sender, EventArgs e)
        {
            
            Persistance.OpenLayer();
            f1.AddLayer();
            if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPointLayer)
            {
                f1.Temp.Image = ((CPointLayer)Controller.CurrentLayer).drawpoint();
            }
            else if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CLineLayer)
            {
                f1.Temp.Image = ((CLineLayer)Controller.CurrentLayer).drawlinelayer();
            }
            else if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPolygonLayer)
            {
                f1.Temp.Image = ((CPolygonLayer)Controller.CurrentLayer).drawpolygon();
            }
            else if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CTextLayer)
            {
                f1.Temp.Image = ((CTextLayer)Controller.CurrentLayer).drawtext();
            }
            LayerButton();
            ChildNode = new TreeNode(Controller.MyMap.Layer_List[Controller.CountLayer - 1].Name);
            CurrentLayerCombo.DataSource = null;
            CurrentLayerCombo.DataSource = Controller.MyMap.Layer_List;
            CurrentLayerCombo.DisplayMember = "GetName";
            CurrentLayerCombo.SelectedIndex = Controller.CountLayer - 1;
            ChildNode.Name = "childnode" + Controller.CountLayer;
            ChildNode.ImageIndex = 1;
            ChildNode.SelectedImageIndex = 1;
            ParentNode.Nodes.Insert(0, ChildNode);
            ChildNode.Checked = true;
            LayerTree.ExpandAll();
            Controller.current_Operation = Controller.OperationStyles.None;
            Controller.MyMap.ModifyLayerOrder();
        }

        private void CloseMap()
        {
            ParentNode.Nodes.Clear();
            ParentBaseNode.Nodes.Clear();
            ParentNode.Text = "地图列表";
            ParentBaseNode.Text = "底图列表";
            try
            {
                for (int i = 0; i < Controller.MyMap.Layer_Order.Count; i++)
                {
                    Controller.FindLayer(Controller.MyMap.Layer_Order[i]).Dispose();
                }
                for (int i = 0; i < Controller.MyMap.Base_Order.Count; i++)
                {
                    Controller.FindBase(Controller.MyMap.Base_Order[i]).Dispose();
                }
                f1.panelbase.Controls.RemoveAt(0);
                f1.Dispose();
                Controller.Dispose();
            }
            catch
            {
                return;
            }
            AddLayer.Enabled = false;
            Save.Enabled = false;
            Export.Enabled = false;
            Import.Enabled = false;
            AddLayer.Enabled = false;
            NewLayer.Enabled = false;
            NewDB.Enabled = false;
            panelmdi.Visible = false;
            ptLayerFirstLegend = true;
            lnLayerFirstLegend = true;
            plgLayerFirstLegend = true;
            txLayerFirstLegend = true;
            toolStriptool.Enabled = false;
            toolStriptool.Enabled = false;
            toolStripedit.Enabled = false;
            IDGenerator.Reset();    //ID清零
        }
        private void OpenMap_Click(object sender, EventArgs e)
        {
            Persistance.OpenMap();
            if (Controller.check == true)
            {
                MapButton();
                ParentNode.Text = Controller.MyMap.Name;
                panelmdi.Visible = true;
                Controller.View_Height = 701;
                Controller.View_Width = 1080;
                panelmdi.Visible = true;
                f1 = new Childform();
                Controller.CountForm++;
                f1.FormBorderStyle = FormBorderStyle.None;
                f1.Height = 464;
                f1.Width = 758;
                f1.MdiParent = this;
                f1.Parent = this.panelmdi;
                f1.Text = "子窗体" + Controller.CountForm;
                if (this.WindowState == FormWindowState.Maximized)
                {
                    f1.Width = 1080;
                    f1.Height = 701;
                }
                f1.Show();
                MapButton();
                
                for (int i = 0; i < Controller.MyMap.Layer_List.Count; i++)
                {
                    f1.AddLayer();
                    if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPointLayer)
                    {
                        f1.Temp.Image = ((CPointLayer)Controller.CurrentLayer).drawpoint();
                    }
                    else if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CLineLayer)
                    {
                        f1.Temp.Image = ((CLineLayer)Controller.CurrentLayer).drawlinelayer();
                    }
                    else if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CPolygonLayer)
                    {
                        f1.Temp.Image = ((CPolygonLayer)Controller.CurrentLayer).drawpolygon();
                    }
                    else if (Controller.CurrentLayer.Layer_Type == CLayer.LayerType.CTextLayer)
                    {
                        f1.Temp.Image = ((CTextLayer)Controller.CurrentLayer).drawtext();
                    }
                    ChildNode = new TreeNode(Controller.MyMap.Layer_List[Controller.CountLayer - 1].Name);
                    CurrentLayerCombo.DataSource = null;
                    CurrentLayerCombo.DataSource = Controller.MyMap.Layer_List;
                    CurrentLayerCombo.DisplayMember = "GetName";
                    CurrentLayerCombo.SelectedIndex = Controller.CountLayer - 1;
                    ChildNode.Name = "childnode" + Controller.CountLayer;
                    ChildNode.ImageIndex = 1;
                    ChildNode.SelectedImageIndex = 1;
                    ParentNode.Nodes.Insert(0, ChildNode);
                    ChildNode.Checked = true;
                    LayerTree.ExpandAll();
                    Controller.current_Operation = Controller.OperationStyles.None;
                    Controller.MyMap.ModifyLayerOrder();
                    Controller.check = false;
                }
                toolStripStatusUnit.Text += Controller.MyMap.Unit;
                toolStripStatusLabelScale.Text += "1:1";
            }
        }

        private void Island_Click(object sender, EventArgs e)
        {
            DialogResult drt= MessageBox.Show("岛是否是一个单独多边形？", "画岛", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
            if (drt == DialogResult.Yes)
            {
                f1.drawisland = true;
                f1.addislandpolygon = true;
            }
            if (drt == DialogResult.No)
            {
                f1.drawisland = true;
                f1.addislandpolygon = false;
            }
            f1.Cursor = HandCursor;
        }

        private void Close_Click(object sender, EventArgs e)
        {
            CloseMap();
        }

        private void AddData_Click(object sender, EventArgs e)
        {
            if(NewLayer.Enabled)
                NewLayer.PerformClick();
        }

        private void ExportMap_Click(object sender, EventArgs e)
        {
            if(Export.Enabled)
                Export.PerformClick();
        }

        //修改图层属性
        private void LayerProp_Click(object sender, EventArgs e)
        {
            LayerPropForm layerPropForm = new LayerPropForm();
            int curLayerID = Convert.ToInt16(selectNode.Name.Replace("childnode", ""));
            layerPropForm.initializeForm(curLayerID);
            layerPropForm.Text = Controller.MyMap.Layer_List[curLayerID - 1].Name;
            layerPropForm.ShowDialog();
        }


    }
}
